package com.xiaren.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 模拟第三方缓存配合spring事务的操作
 * @Author xiaren
 * @Date 18/12/15 22:52
 **/
@Configuration
public class DemoCacheConfig {

    public static Map<String, Object> mapStore = new HashMap<>();


    /**
     * 模拟正常缓存提交条件
     * @param key
     * @param value
     */
    public void put(String key, Object value) {
        // 事务细节begin ------ (模拟redis与spring事务结合)
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCompletion(int status) {
                if (status == TransactionSynchronization.STATUS_COMMITTED) {
                    // spring事务正确提交，则这边也提交
                    mapStore.put(key, value);
                } else {
                    // spring 事务不正确执行，则这边不做操作
                }
            }
        });
        // 事务细节end ------------
    }

    /**
     * 模拟缓存里面提交报错的情况
     * @param key
     * @param value
     */
    public void putError(String key, Object value) {
        // 事务细节begin ------ (模拟redis与spring事务结合)
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCompletion(int status) {
                if (status == TransactionSynchronization.STATUS_COMMITTED) {
                    // spring事务正确提交，则这边也提交
                    int i = 1 / 0;
                    mapStore.put(key, value);
                } else {
                    // spring 事务不正确执行，则这边不做操作
                }
            }
        });
        // 事务细节end ------------
    }




}
